import React, { useEffect, useState } from 'react'
import { Tabs } from 'antd'
import PagePane from './PagePane'
import './index.less'
import GraphStylePane from './GraphStylePane'
import { mxCell } from 'mxgraph'
import EditorExecutor from '@/executor/EditorExecutor'
import Editor from '../Editor'
import DataPane from './DataPane'

export default function PropsTabs(props: { editor: Editor }) {
  // 当前Tab的选中key
  const [activeKey, setActiveKey] = React.useState('page')
  const [cells, setCells] = useState<mxCell[]>([])

  const onCellChange = () => {
    const graph = EditorExecutor.graph
    const cells = graph.getSelectionCells()
    console.log('cells 发生变化', cells)
    if (activeKey !== 'data') {
      if (cells?.length == 0) {
        setActiveKey('page')
      } else {
        setActiveKey('graph')
      }
    }

    setCells(cells)
  }

  useEffect(() => {
    if (props.editor) {
      EditorExecutor.graph.model.addListener(mxEvent.CHANGE, onCellChange)
      EditorExecutor.graph.getSelectionModel().addListener(mxEvent.CHANGE, onCellChange)

      return () => {
        EditorExecutor.graph.model.removeListener(onCellChange)
        EditorExecutor.graph.getSelectionModel().removeListener(onCellChange)
      }
    }
  }, [props.editor, activeKey])
  const onChange = (key: string) => {
    setActiveKey(key)
  }

  return (
    <Tabs
      defaultActiveKey="1"
      activeKey={activeKey}
      items={[
        {
          key: 'page',
          label: '页面样式',
          children: <PagePane editor={props.editor} />
        },
        {
          key: 'graph',
          label: '图形样式',
          children: <GraphStylePane cells={cells} />
        },
        {
          key: 'data',
          label: '数据',
          children: <DataPane cells={cells} />
        }
      ]}
      onChange={onChange}
      className="props-tabs "
      tabBarStyle={{ fontSize: '13px' }}
    />
  )
}
